package com.free.front.bf.product;

import com.deco.domain.vo.product.CatagoryLogVo;
import com.deco.domain.vo.product.DicVehicleVo;
import com.deco.domain.vo.product.PartGroupVo;
import com.deco.domain.vo.ti.TiDelcoPartGroupVo;
import com.deco.service.product.CatagoryLogService;
import com.deco.service.product.DicVehicleService;
import com.deco.service.product.PartGroupService;
import com.deco.service.ti.TiDelcoPartGroupService;
import com.deco.service.ti.TiDmsPartMainService;
import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.free.front.util.ChangeUtil;
import com.free.front.util.Mu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;

import java.math.BigDecimal;
import java.text.Collator;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 功能概述:
 * </p>
 * <p>
 * 功能详述:
 * </p>
 */
@Component
public class ProductSearchBf {
    /*========================================================================*
     *                         Public Fields (公共属性)
     *========================================================================*/

    /*========================================================================*
     *                         Private Fields (私有属性)
     *========================================================================*/


    private static final FreeLogger LOG = FreeLoggerFactory.getLogger(ProductSearchBf.class);

    @Autowired
    private TiDelcoPartGroupService delcoPartGroupService;

    @Autowired
    private TiDmsPartMainService dmsPartMainService;

    @Autowired
    private DicVehicleService dicVehicleService;

    @Autowired
    private PartGroupService partGroupService;

    @Autowired
    private CatagoryLogService catagoryLogService;

    @Value(value = "${sys.target.floder}")
    private String infoPath;
    /*========================================================================*
     *                         Construct Methods (构造方法)
     *========================================================================*/

    /*========================================================================*
     *                         Public Methods (公有方法)
     *========================================================================*/

    // ----------------- 按车型检索 ------------------- //
    public List<DicVehicleVo> queryBrandList(){
        return dicVehicleService.selectBrandList1(null);
    }

    public List<DicVehicleVo> getProdType(DicVehicleVo vo){
        return dicVehicleService.selectModelList1(Mu.beanToMap(vo));
    }

    public List<DicVehicleVo> getProDdet(DicVehicleVo vehicle){
        return dicVehicleService.selectDetType1(Mu.beanToMap(vehicle));
    }

    // ----------------- 按车型检索 ------------------- //
    // ----------------- 按零件检索 ------------------- //
    public List<String> queryPartNumberList(){
        List<String> res = new ArrayList<>();
        TiDelcoPartGroupVo vo = new TiDelcoPartGroupVo();
        List<String> pgs = delcoPartGroupService.selectPartNumberList();
        List<String> partnumbers = dmsPartMainService.selectPartNumberList();
        res.addAll(pgs);
        res.addAll(partnumbers);
        return res;
    }

    public Map<String, Object> getPartNumber(DicVehicleVo dicVehicle){
        Map<String, Object> param=new HashMap<String, Object>();
        // List<String> partNumberList = dicVehicleDao.selectList(MybatisUtils.getMapperKey(DicVehicle.class, "resList"), Mu.beanToMap(dicVehicle));
        List<DicVehicleVo> partNumberList1 = dicVehicleService.partList(dicVehicle);
        List<Map<String, Object>> partNumberList2 =dicVehicleService.desList(Mu.beanToMap(dicVehicle));
        List<Map<String, Object>> partNumberList3 =dicVehicleService.selectVehicleNoByPart1(Mu.beanToMap(dicVehicle));
        List<DicVehicleVo> partNumberList4 = dicVehicleService.desList1(dicVehicle);
        List<Map<String, Object>> partList= dicVehicleService.resList1(Mu.beanToMap(dicVehicle));

        param.put("resList", zhuan(partList));
        param.put("partList", partNumberList1);//参数信息
        param.put("desList", ChangeUtil.zhuanPart(partNumberList2));
        param.put("lj", infoPath);
        param.put("desList1", partNumberList4);//图片url
        param.put("selectVehicleNoByPart", ChangeUtil.zhuanCheXing(partNumberList3));//适配车型
        return  param;
    }

    // ----------------- 按零件检索 ------------------- //

    public Map<String,Object> getCd(){
        Map<String, Object> param=new HashMap<String, Object>();
        List<Map<String, Object>> partNumberList = dicVehicleService.getCd(null);
        param.put("cd", ChangeUtil.zhuanCd(partNumberList));
        return param;
    }

    public Map<String,Object> getMdCd(){
        Map<String, Object> param=new HashMap<String, Object>();
        List<Map<String, Object>> partNumberList = dicVehicleService.getMdCd(null);
        param.put("cd", ChangeUtil.zhuanMdCd(partNumberList));
        return param;
    }

    public List<Map<String, Object>> tyreList(DicVehicleVo vehicle){
        List<Map<String, Object>> tyreList=null;
        int aa=0;
        Map<String, Object> a=new HashMap<String, Object>();
        if(vehicle.getReserve1().length()!=0&&
                vehicle.getReserve2().length()!=0&&vehicle.getReserve3().length()!=0&&aa==0){
            tyreList = dicVehicleService.selectTyreList2(Mu.beanToMap(vehicle));
            aa=1;
        }
        if(vehicle.getReserve1().length()==0&&
                vehicle.getReserve2().length()!=0&&vehicle.getReserve3().length()!=0&&aa==0){
            vehicle.setReserve1(vehicle.getReserve2());
            vehicle.setReserve2(vehicle.getReserve3());
            vehicle.setReserve3("");
            vehicle.setReserve4("CRIAMI021");
            vehicle.setReserve5("CRIAMI116");
            tyreList = dicVehicleService.selectTyreList4(Mu.beanToMap(vehicle));
            aa=1;
        }
        if(vehicle.getReserve1().length()==0&&
                vehicle.getReserve2().length()==0&&vehicle.getReserve3().length()!=0&&aa==0){
            vehicle.setReserve1(vehicle.getReserve3());
            vehicle.setReserve3("");
            vehicle.setReserve4("CRIAMI116");
            tyreList = dicVehicleService.selectTyreList5(Mu.beanToMap(vehicle));
            aa=1;
        }
        if(vehicle.getReserve1().length()==0&&
                vehicle.getReserve2().length()!=0&&vehicle.getReserve3().length()==0&&aa==0){
            vehicle.setReserve1(vehicle.getReserve2());
            vehicle.setReserve2("");
            vehicle.setReserve4("CRIAMI021");
            tyreList = dicVehicleService.selectTyreList5(Mu.beanToMap(vehicle));
            aa=1;
        }
        if(vehicle.getReserve1().length()!=0&&
                vehicle.getReserve2().length()==0&&vehicle.getReserve3().length()==0&&aa==0){
            vehicle.setReserve4("CRIAMI113");
            tyreList = dicVehicleService.selectTyreList5(Mu.beanToMap(vehicle));
            aa=1;
        }
        if(vehicle.getReserve1().length()!=0&&
                vehicle.getReserve2().length()==0&&vehicle.getReserve3().length()!=0&&aa==0){
            vehicle.setReserve2(vehicle.getReserve3());
            vehicle.setReserve3("");
            vehicle.setReserve4("CRIAMI114");
            vehicle.setReserve5("CRIAMI021");
            tyreList = dicVehicleService.selectTyreList4(Mu.beanToMap(vehicle));
            aa=1;
        }
        if(vehicle.getReserve1().length()!=0&&
                vehicle.getReserve2().length()!=0&&vehicle.getReserve3().length()==0&&aa==0){
            vehicle.setReserve4("CRIAMI113");
            vehicle.setReserve5("CRIAMI021");
            tyreList = dicVehicleService.selectTyreList4(Mu.beanToMap(vehicle));
            aa=1;
        }
        List<Map<String, Object>> tyreList1=zhuan(tyreList);
        return  tyreList1;
    }

    public List<String> getProdDis(DicVehicleVo vehicle){
        List<DicVehicleVo> res = dicVehicleService.selectDisplacementl1(Mu.beanToMap(vehicle));
        List<String> strings = new ArrayList<>();
        if(res != null && res.size() >0){
            res.forEach(x->{
                if(x!= null){
                    strings.add(x.getDisplacementL());
                }
            });
        }
        return strings;
    }

    public List<Map<String, Object>> prodTeamList1(PartGroupVo partGroup, String ip, String paltForm){
        String[] ips = ip.split(",");
        ip = ips[0];

        CatagoryLogVo log1 = new CatagoryLogVo();
        log1.setIp(ip);
        log1.setPlatform(paltForm);
        log1.setCreateTime(new Date());
        log1.setSublineNo(partGroup.getSublineNo());
        log1.setId(0);
        Map<String, Object> res = partGroupService.carList2(partGroup);
        log1.setSublineName(res.get("SUBLINE_NAME").toString());
        catagoryLogService.save(log1);
        List<Map<String, Object>> paramsList = partGroupService.selectProdTeamList1(partGroup);
        return zhuan(paramsList);
    }

    public Map<String,Object> mprodLtTeamList1(String vehicleNo){
        DicVehicleVo vo = new DicVehicleVo();
        vo.setVehicleNo(vehicleNo);
        Map<String,Object> res = new HashMap<>();
        List<Map<String, Object>> partNumberList2  = dicVehicleService.selectTyreList(Mu.beanToMap(vo));
        res.put("tyreList",ChangeUtil.zhuanLunTai(partNumberList2));

        List<Map<String, Object>> partNumberList1 = dicVehicleService.selectTyreList6(Mu.beanToMap(vo));
        res.put("tyreList1",ChangeUtil.zhuanPart2(partNumberList1));
        res.put("carlist",dicVehicleService.carList2(vo)) ;
        return res;
    }

    public Map<String,Object> mprodTeamList1(PartGroupVo partGroup, String vehicleNo, String ip, String paltForm){
        String[] ips = ip.split(",");
        ip = ips[0];
        CatagoryLogVo log1 = new CatagoryLogVo();
        log1.setIp(ip);
        log1.setPlatform(paltForm);
        log1.setCreateTime(new Date());
        log1.setSublineNo(partGroup.getSublineNo());
        log1.setId(0);
        Map<String, Object> res = partGroupService.carList2(partGroup);
        log1.setSublineName(res.get("SUBLINE_NAME").toString());
        catagoryLogService.save(log1);

        List<Map<String, Object>> paramsList = partGroupService.selectProdTeamList1(partGroup);
        Map<String,Object> parRes = new HashMap<>();
        parRes.put("paramsList",zhuan(paramsList));
        parRes.put("SUBLINE_NAME",res.get("SUBLINE_NAME").toString());
        if(StringUtils.isNotEmpty(vehicleNo)){
            Map<String,Object> params = new HashMap<>();
            params.put("vehicleNo",vehicleNo);
            List<Map<String,Object>> carList = dicVehicleService.carList(params);
            parRes.put("carList",carList);
        }
        return parRes;
    }

    public Map<String,Object> getPartInfo(PartGroupVo partGroup, String ip, String paltForm){
        String[] ips = ip.split(",");
        ip = ips[0];
        CatagoryLogVo log1 = new CatagoryLogVo();
        log1.setIp(ip);
        log1.setPlatform(paltForm);
        log1.setCreateTime(new Date());
        log1.setSublineNo(partGroup.getSublineNo());
        log1.setId(0);
        Map<String, Object> res = partGroupService.carList2(partGroup);
        log1.setSublineName(res.get("SUBLINE_NAME").toString());
        catagoryLogService.save(log1);
        List<Map<String, Object>> paramsList = partGroupService.selectProdTeamList1(partGroup);
        Map<String,Object> parRes = new HashMap<>();
        parRes.put("paramsList",zhuan(paramsList));
        parRes.put("SUBLINE_NAME",res.get("SUBLINE_NAME").toString());
        Map<String,Object> carList = partGroupService.carList2(partGroup);
        parRes.put("carList",carList);
        return parRes;
    }

    public Map<String,Object> getPartDet(DicVehicleVo vo){
        Map<String, Object> param=new HashMap<String, Object>();
        List<DicVehicleVo> partNumberList = dicVehicleService.selectAbleProd(vo);
        List<DicVehicleVo> partNumberSGMDList = dicVehicleService.selectAbleProdSGMD(vo);
        List<Map<String, Object>> partNumberList2 = dicVehicleService.selectTyreList(Mu.beanToMap(vo));
        param.put("AbleProd", partNumberList);//适用产品
        param.put("AbleProdSGMD", partNumberSGMDList);//适用产品
        param.put("tyreList",ChangeUtil.zhuanLunTai(partNumberList2));
        return param;
    }

    /**
     * Vin检索时查询详情信息
     * @param vehicleNo
     * @return
     */
    public Map<String,Object> getPartDetAndCarInfo(String vehicleNo){
        DicVehicleVo params = new DicVehicleVo();
        params.setVehicleNo(vehicleNo);
        List<Map<String,Object>> carList = dicVehicleService.carList2(params);
        LOG.info("VIN查询编号：{}查到的汽车数量{}",vehicleNo, carList.size());
        if(carList == null || carList.size() ==0){
            return null;
        }
        DicVehicleVo vo = new DicVehicleVo();
        vo.setVehicleNo(vehicleNo);
        Map<String,Object> res = getPartDet(vo);
        res.put("carInfo",carList.get(0));
        if(res != null){
            res.put("vechileNo",vehicleNo);
        }
        return res;
    }

    public Map<String,Object> mgetPartDet(DicVehicleVo vo){
        Map<String, Object> param=new HashMap<String, Object>();
        List<DicVehicleVo> partNumberList = dicVehicleService.selectAbleProd(vo);
        List<DicVehicleVo> partNumberSGMDList = dicVehicleService.selectAbleProdSGMD(vo);
        List<Map<String, Object>> partNumberList2 = dicVehicleService.selectTyreList(Mu.beanToMap(vo));
        List<Map<String,Object>> carList = dicVehicleService.carList(Mu.beanToMap(vo));
        param.put("AbleProd", partNumberList);//适用产品
        param.put("AbleProdSGMD", partNumberSGMDList);//适用产品
        param.put("tyreList",ChangeUtil.zhuanLunTai(partNumberList2));
        param.put("carList",carList);
        return param;
    }

    public List<Map<String, Object>> gettyreList(DicVehicleVo vo){

        List<Map<String, Object>> tyreList=  dicVehicleService.selectTyreList1(Mu.beanToMap(vo));
        List<Map<String, Object>> carlist = dicVehicleService.carList1(vo);
        Map<String, Object> carMap = carlist.get(0);
        List<Map<String, Object>> tyStrings=ChangeUtil.zhuanPart2(tyreList);
        tyreList.add(carMap);
        return tyStrings;
    }

    public Map<String,Object> mgettyreList(PartGroupVo partGroup, String vehicleNo, String ip, String paltForm){

        String[] ips = ip.split(",");
        ip = ips[0];
        CatagoryLogVo log1 = new CatagoryLogVo();
        log1.setIp(ip);
        log1.setPlatform(paltForm);
        log1.setCreateTime(new Date());
        log1.setSublineNo(partGroup.getSublineNo());
        log1.setId(0);
        Map<String, Object> res = partGroupService.carList2(partGroup);
        log1.setSublineName(res.get("SUBLINE_NAME").toString());
        catagoryLogService.save(log1);
        DicVehicleVo vo = new DicVehicleVo();
        vo.setVehicleNo(vehicleNo);
        vo.setTransType(partGroup.getSublineNo());
        Map<String,Object> parRes = new HashMap<>();
        if("10C,10E,10F,10B,10J".indexOf(partGroup.getSublineNo()) >= 0){
            List<Map<String, Object>> paramsList = partGroupService.selectProdTeamList1(partGroup);
            parRes.put("paramsList",zhuan(paramsList));
        }else{
            List<Map<String, Object>> paramsList=  dicVehicleService.selectTyreList1(Mu.beanToMap(vo));
            parRes.put("paramsList",ChangeUtil.zhuanPart2(paramsList));
        }
        parRes.put("SUBLINE_NAME",res.get("SUBLINE_NAME").toString());
        if(StringUtils.isNotEmpty(vehicleNo)){
            Map<String,Object> params = new HashMap<>();
            params.put("vehicleNo",vehicleNo);
            List<Map<String,Object>> carList = dicVehicleService.carList(params);
            parRes.put("carList",carList);
        }
        return parRes;
    }

    public Map<String, Object> getPartNumber3(DicVehicleVo dicVehicle){
        Map<String, Object> param=new HashMap<String, Object>();
        // List<String> partNumberList = dicVehicleDao.selectList(MybatisUtils.getMapperKey(DicVehicle.class, "resList"), Mu.beanToMap(dicVehicle));
        List<DicVehicleVo> partNumberList1 = dicVehicleService.partList(dicVehicle);
        List<Map<String, Object>> partNumberList2 =dicVehicleService.desList(Mu.beanToMap(dicVehicle));
        List<Map<String, Object>> partNumberList3 =dicVehicleService.selectVehicleNoByPart1(Mu.beanToMap(dicVehicle));
        List<DicVehicleVo> partNumberList4 = dicVehicleService.desList1(dicVehicle);
        List<Map<String, Object>> partList= dicVehicleService.resList1(Mu.beanToMap(dicVehicle));

        param.put("resList", zhuan(partList));
        param.put("partList", partNumberList1);//参数信息
        param.put("desList", ChangeUtil.zhuanPart(partNumberList2));
        param.put("lj", infoPath);
        param.put("desList1", partNumberList4);//图片url
        param.put("selectVehicleNoByPart1", ChangeUtil.zhuanCheXing(partNumberList3));//适配车型
        return  param;
    }

    /*========================================================================*
     *                         Private Methods (私有方法)
     *========================================================================*/

    public List<Map<String, Object>> zhuan(List<Map<String, Object>> paramsList1){
        int tempNum = 0;
        List<Map<String, Object>> paramsList = new ArrayList<Map<String, Object>>();
        paramsList=paramsList1;
        List<List<Map<String, Object>>> groupLists = new ArrayList<List<Map<String, Object>>>();
        List<Map<String, Object>> groupList = null;
        String tempGroupNum = "";
        for (int i = 0; i < paramsList.size(); i++) {
            Map<String, Object> params = paramsList.get(i);
            // 区分组信息
            if (!tempGroupNum.equals(params.get("PART_NUMBER").toString())) {
                if (null != groupList) {
                    groupLists.add(groupList);
                }
                groupList = new ArrayList<Map<String, Object>>();
                tempGroupNum = params.get("PART_NUMBER").toString();
            }
            groupList.add(params);
            if (i == paramsList.size() - 1) {
                groupLists.add(groupList);
            }
        }
        System.out.println(groupLists);

        // 遍历组数据，将组数据转换为行数据
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        for (List<Map<String, Object>> group : groupLists) {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            int a=0;
            //Object [] name=new Object[10];
            Object [] name=new Object[10];
            //Object [] value=new Object[10];
            Object [] value=new Object[10];
            for (Map<String, Object> param : group) {
                a++;
                resultMap.put("PART_NUMBER", param.get("PART_NUMBER"));
                resultMap.put("PART_NAME_CN", param.get("SUBLINE_NAME"));
                //resultMap.put(param.get("PARA_NAME").toString(), param.get("PARA_VALUE"));
                if("产品系列".equals(param.get("PARA_NAME"))){
                    resultMap.put("prodLine", param.get("PARA_VALUE"));}
                else{

                    name[a]=ChangeUtil.kString(param.get("PARA_NAME"));
                    value[a]=ChangeUtil.kString(param.get("PARA_VALUE"));
                }
            }

            List<String> tmp = new ArrayList<String>();
            for(Object str:name){
                if(str!=null && ((String) str).length()!=0){
                    tmp.add((String) str);
                }
            }
            List<String> tmp1 = new ArrayList<String>();
            for(Object str:value){
                if(str!=null && ((String) str).length()!=0){
                    tmp1.add((String) str);
                }
            }
            name = tmp.toArray(new String[0]);
            value = tmp1.toArray(new String[0]);
            resultMap.put("name",name);
            resultMap.put("value",value);

            //resultList.addAll(ChangeUtil.zhuan(paramsList1));
            resultList.add(resultMap);
        }
        System.out.println(resultList);
        if(resultList.size() >0 ){
            Collections.sort(resultList,new Comparator<Map<String, Object>>(){

                @Override
                public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
                    Object[] value0 = (Object[])arg0.get("value");
                    Object[] value1 = (Object[])arg1.get("value");
                    if(value0 == null || value0.length == 0 || value1 == null || value1.length == 0){
                        return 1;
                    }
                    if(isChinese(value0[0].toString()) && isChinese(value1[0].toString()))
                    {
                        Collator collator = Collator.getInstance(Locale.CHINA);
                        return collator.compare(value0[0].toString(), value1[0].toString());
                    }
                    else if(isNumeric(value0[0].toString()) && isNumeric(value1[0].toString()))
                    {
                        BigDecimal bigValue0 = new BigDecimal(value0[0].toString());
                        BigDecimal bigValue1 = new BigDecimal(value1[0].toString());
                        return bigValue0.compareTo(bigValue1);
                    }
                    else{
                        return value0[0].toString().compareTo(value1[0].toString());
                    }
                }
            });
        }
        return resultList;
    }

    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    public static boolean isChinese(String str) {
        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(str);
        boolean flg = false;
        if (matcher.find())
            flg = true;

        return flg;
    }

}
